#include "../../include/CacheManager.h"
#include "../../include/Configuration.h"
#include <fstream>

using std::ifstream;

//单例
CacheManager *CacheManager::_pInstance = nullptr;
CacheManager::AutoRelease CacheManager::_ar;

string getLRUCacheDat() {
    return Configuration::getInstance()->getConfigValue("LRUCACHE_DAT");
}

CacheManager* CacheManager::getInstance()
{
    if(!_pInstance){
        _pInstance = new CacheManager();
        _pInstance->initCache(getLRUCacheDat());
    }
    return _pInstance;
}

void CacheManager::initCache(const string &filename) //从磁盘文件中读取缓存信息
{
    string threadNum = Configuration::getInstance()->getConfigValue("THREAD_NUM");
    int threadSize = atoi(threadNum.c_str());

    _cacheList.resize(threadSize);
    for (int i = 0; i < threadSize;++i){
        _cacheList[i].readFromFile(filename);
    }
}

LRUCache &CacheManager::getCache(size_t idx) //获取某个缓存
{
    return _cacheList[idx];
}

void CacheManager::periodicUpdateCaches() //定时更新所有缓存
{
    // 同步更新与持久化
    for (size_t i = 0; i != _cacheList.size();++i){
        _cacheList[0].update(_cacheList[i]);
        _cacheList[i].clearPendingList(); //清空pendingList
    }

    _cacheList[0].writeToFile(getLRUCacheDat());

    //0号的resultList复制到1~4号的resultList中
    for (size_t i = 1; i != _cacheList.size();++i){
        _cacheList[i].updateAll(_cacheList[0]);
    }
}
